package com.gjxjl.jdbc.gateway;


import com.gjxjl.jdbc.gateway.config.ProxyConfig;
import com.gjxjl.jdbc.gateway.handler.BackendConnector;
import com.gjxjl.jdbc.gateway.handler.MySQLProtocolHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class JdbcGatewayServer {
    private static final Logger logger = LogManager.getLogger(JdbcGatewayServer.class);

    private final ProxyConfig config;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public JdbcGatewayServer() {
        this.config = new ProxyConfig();
    }

    public void start() throws InterruptedException {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new MySQLProtocolHandler(config));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true);

            int port = config.getProxyPort();
            ChannelFuture future = bootstrap.bind(port).sync();

            logger.info("JDBC Proxy Server started on port {}", port);
            logger.info("Backend database: {}:{}",
                    config.getBackendHost(), config.getBackendPort());
            logger.info("Security features: {}",
                    config.isEnableLogging() ? "Logging enabled" : "Logging disabled");

            future.channel().closeFuture().sync();
        } finally {
            stop();
        }
    }

    public void stop() {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        BackendConnector.shutdown();
        logger.info("JDBC Proxy Server stopped");
    }

    public static void main(String[] args) {
        JdbcGatewayServer server = new JdbcGatewayServer();

        // Add shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("Shutting down JDBC Proxy Server...");
            server.stop();
        }));

        try {
            server.start();
        } catch (InterruptedException e) {
            logger.error("Server interrupted", e);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            logger.error("Server error", e);
        }
    }
}
